import { updateRobotService, updateAdvisorStarService } from '@/api'
import { BaseSelect } from '@/components'
import { SET_SNACKBAR } from '@/store/actions'
import { ServiceList, IconList, ColorList } from '@/store/constant'
import { StarItem, StarServiceItem } from '@/types/common'
import { ServiceStatusEnum } from '@/types/enum'
import { SelectChangeEvent } from '@mui/material'
import { ChangeEvent } from 'react'

type Props = {
  row: StarItem
  refresh: () => void
  renderTrigger?: (props: any) => React.ReactNode
}

const ServiceOptions = [
  { label: '🟢 开放', value: ServiceStatusEnum.Close },
  { label: '🟠 接单', value: ServiceStatusEnum.Open, disabled: true },
  { label: '❌ 关停', value: ServiceStatusEnum.Shutdown },
  { label: '❌ 暂停', value: ServiceStatusEnum.Suspend, disabled: true }
]

const RobotOption = [
  { label: '🟢 开放', value: ServiceStatusEnum.Open },
  { label: '❌ 关闭', value: ServiceStatusEnum.Close }
]

const FormConfig = [
  { title: '机器人', groupKey: 'robot', list: [{ type: -1, label: 'Robot' }], options: RobotOption },
  {
    title: '服务设置',
    groupKey: 'services',
    list: ServiceList,
    options: ServiceOptions
  }
]

const getFormData = (row: StarItem) => {
  return {
    '-1': { status: get(row.robot, 'robot_status') }, // 机器人的type为-1
    ...mapValues(keyBy(row.services, 'type'), (v: StarServiceItem) => pick(v, ['price', 'status']))
  }
}

const UpdateServiceButton = ({ row, refresh, renderTrigger }: Props) => {
  const theme = useTheme()
  const dispatch = useDispatch()
  const [open, setOpen] = useState(false)
  const defaultFormData = useMemo(() => {
    return getFormData(row)
  }, [row])

  const [formData, setFormData] = useState(defaultFormData)

  const handleClose = () => {
    setOpen(false)
  }
  const handleOpen = () => {
    setOpen(true)
  }

  const fullScreen = useMediaQuery(theme.breakpoints.down('sm'))
  const onFinally = (_params: any, _data: any, error: Error | undefined) => {
    handleClose()
    dispatch({
      type: SET_SNACKBAR,
      payload: {
        severity: error ? 'error' : 'success',
        children: (
          <>
            <AlertTitle>{error ? '失败: ' + error.message : '操作成功！'}</AlertTitle>
            {row.name}
          </>
        )
      }
    })
  }

  // 更新机器人的服务
  const { runAsync: robotRunAsync, loading: robotLoading } = useRequest(updateRobotService, {
    manual: true,
    debounceWait: 500,
    onSuccess() {
      refresh()
    },
    onFinally
  })

  // 更新接单服务
  const { runAsync, loading } = useRequest(updateAdvisorStarService, {
    manual: true,
    debounceWait: 500,
    onSuccess() {
      refresh()
    },
    onFinally
  })

  const updatedServices = useMemo(() => {
    // 只传更改项
    const differences = differenceWith(toPairs(formData), toPairs(defaultFormData), (pair1: any, pair2: any) =>
      isEqual(pair1, pair2)
    )
    const diffObject = fromPairs(differences)
    const services = map(
      filter(row.services, (v: StarServiceItem) => has(diffObject, String(v.type))),
      (val: StarServiceItem) => ({ ...val, ...get(diffObject, [val.type]) })
    )
    return services
  }, [formData, defaultFormData])

  const handleSubmit = () => {
    const robotStatus = get(formData, ['-1', 'status'])
    const defaultRobotStatus = get(defaultFormData, ['-1', 'status'])
    const services = updatedServices
    if (!isEqual(robotStatus, defaultRobotStatus)) {
      robotRunAsync({ star_id: row.star_id, robot_status: robotStatus })
    }
    if (!isEmpty(services)) {
      const data = {
        ...pick(row, 'star_id'),
        services
      }
      runAsync(data)
    }
  }
  const handleChange =
    (type: number, key: string) => (e: ChangeEvent<HTMLTextAreaElement | HTMLInputElement> | SelectChangeEvent) => {
      const { value } = e.target
      setFormData({ ...formData, [type]: { ...formData[type], [key]: value !== '' ? Number(value) : value } })
    }

  useEffect(() => {
    setFormData(defaultFormData)
  }, [open])

  return (
    <>
      {renderTrigger ? (
        renderTrigger({ onClick: handleOpen })
      ) : (
        <Button variant="text" onClick={handleOpen} size="small" color="secondary">
          编辑
        </Button>
      )}
      <Dialog
        fullWidth
        maxWidth="xs"
        fullScreen={fullScreen}
        open={open}
        onClose={handleClose}
        PaperProps={{
          component: 'form',
          onSubmit: (event: React.FormEvent<HTMLFormElement>) => {
            event.preventDefault()
            handleSubmit()
          }
        }}
      >
        <DialogTitle fontSize="1rem">
          编辑 &nbsp;
          <Chip size="small" label={row.name} />
        </DialogTitle>
        <DialogContent>
          {FormConfig.map((cell) => {
            const { title, list, groupKey } = cell
            return (
              <Fragment key={groupKey}>
                <List subheader={<ListSubheader>{title}</ListSubheader>}>
                  {list.map((item, index) => {
                    const RenderIcon = IconList[index % IconList.length]
                    const color = ColorList[index % ColorList.length]
                    const { type } = item
                    return (
                      <ListItem key={type} sx={{ paddingBlock: 2 }}>
                        <ListItemAvatar>
                          <Avatar sx={{ bgcolor: color[50] }}>
                            <RenderIcon sx={{ color: color[700] }} />
                          </Avatar>
                        </ListItemAvatar>
                        <ListItemText>{item.label}</ListItemText>
                        <Stack justifyContent="flex-end" direction="row" spacing={1} alignItems="center">
                          {type !== -1 && (
                            <TextField
                              label={item.label}
                              value={get(formData[type], 'price')}
                              disabled={get(formData[type], 'status') === ServiceStatusEnum.Open}
                              size="small"
                              sx={{ width: '6rem' }}
                              type="number"
                              required
                              onChange={handleChange(type, 'price')}
                            />
                          )}
                          <BaseSelect
                            required
                            disabled={type !== -1 && get(formData[type], 'status') === ServiceStatusEnum.Open}
                            size="small"
                            sx={{ width: '6rem' }}
                            options={cell.options}
                            id={String(type)}
                            label={item.label}
                            value={get(formData[type], 'status')}
                            onChange={handleChange(type, 'status')}
                          />
                        </Stack>
                      </ListItem>
                    )
                  })}
                </List>
                <Divider sx={{ mb: 2 }} />
              </Fragment>
            )
          })}
        </DialogContent>
        <DialogActions>
          <Button variant="outlined" onClick={handleClose}>
            取消
          </Button>
          <LoadingButton variant="contained" color="secondary" loading={loading || robotLoading} type="submit">
            应用
          </LoadingButton>
        </DialogActions>
      </Dialog>
    </>
  )
}

export default UpdateServiceButton
